const http = require('http');
const url = require('url');
const fs = require('fs');
const createdir = require('./createdir').mkdir;
const httpUtil = require('./httpUtil');
const userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0';

// let u = `https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496614940030&di=f8585f6701918b894ad8b826d8902c2e&imgtype=0&src=http%3A%2F%2Fa.hiphotos.baidu.com%2Fbaike%2Fw%253D268%2Fsign%3De96d5fc46f81800a6ee58e08893433d6%2Fc2fdfc039245d688ec0a14efa7c27d1ed21b2474.jpg`
let list = [
    'http://mtl.woatb.com/uploadfile/2015/0919/20150919124033362.jpg',
    'http://mtl.woatb.com/uploadfile/2015/0919/20150919124034214.jpg',
    'http://mtl.woatb.com/uploadfile/2015/0919/20150919124035133.jpg',
    'http://mtl.woatb.com/uploadfile/2015/0919/20150919124036119.jpg',
    'http://mtl.woatb.com/uploadfile/2015/0919/20150919124036769.jpg',
    'http://mtl.woatb.com/uploadfile/2015/0919/20150919124036311.jpg'
]

let downloadUrl = function(u, dir, filename) {
    createdir(dir)
    httpUtil.getUrl(u)
        .then(function(buf) {
            filename = filename.toString().indexOf('.') > -1 ? filename : filename + '.jpg'
            fs.writeFile(`${dir}/${filename}`, buf, function() {})
        })
        .catch(err => {
            throw err
        })
}

function test() {
    for (let i = 1; i <= list.length; i++) {
        downloadUrl(list[i - 1], 'aaa/download3/shs', `${i}`)
    }
}
// test()

exports.downloadUrl = downloadUrl